package kr.hkit.androidcomplete01.ch19;

import kr.hkit.androidcomplete01.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class BackWork4 extends Activity {

	TextView mResult;
	ProgressDialog mProgress;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_backwork);
		mResult = (TextView) findViewById(R.id.result);
	}

	public void mOnClick(View v) {
		new AccumulateTask().execute(0, 100);
	}

	class AccumulateTask extends AsyncTask<Integer, Integer, Integer> {
		protected void onPreExecute() {
			mProgress = new ProgressDialog(BackWork4.this);
			mProgress.setTitle("WaitTest");
			mProgress.setMessage("Now calculating");
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setCancelable(false);
			mProgress.setOnCancelListener(new OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					cancel(true);
				}
			});
			mProgress.show();
		}

		protected void onPostExecute(Integer result) {
			mProgress.dismiss();
		}

		protected void onProgressUpdate(Integer... values) {
			mProgress.setProgress(values[0]);
			mResult.setText(Integer.toString(values[1]));
		}

		protected void onCancelled() {
			mProgress.dismiss();
		}

		protected Integer doInBackground(Integer... params) {
			int sum = 0;
			for (int i = params[0]; i <= params[1]; i++) {
				sum += i;
				publishProgress(i, sum);
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					;
				}
			}
			return sum;
		}
	}
}
